var app = getApp(),
  a = app.requirejs("core"),
  info = app.getCache("userinfo");
module.exports = {


  //获取表单
  get_form_list:function(id,that){
    var form = app.siteInfo.form,data={};
    var button_name = '提交';
    a.get('index/form',{
      id:id
    },function(t){
      console.log(t)
        if(t.code==0){
          // 使用 decodeURIComponent 的时候报错 Uncaught URIError: URI malformed,因为字符串中可能包含%,需要对其进行转义
          var title = t.info.title.replace(/%/g,'%25');
          wx.setNavigationBarTitle({
            title: t.info.title ? decodeURIComponent(title) : '万能表单'
          }) 
          var form=t.info.list;
          if(form.length==0){
            a.alert('表单内容为空');
            return;
          }
          form.forEach(function(k){
            if (k.module=='picker'){
              data[k.name] = 0;
            };
            if (k.module == 'time_one') {
              data[k.name] = k.default;
            };
            if (k.module == 'time_two') {
              data[k.name + '_1'] = k.default1;
              data[k.name + '_2'] = k.default2;
              if (k.default1 && k.default2){
                data[k.name] = k.default1 + ',' + k.default2;
              }else{
                data[k.name]='';
              }
            };
            if (k.module == 'pic_arr') {
              data[k.name] = [];
            };
            if (k.module == 'region'){
              data[k.name] = k.default;
              data[k.name +'_multi'] = [0, 0, 0];
            }
            
            if (k.module == 'button') {
              button_name = k.title;
            };
          })
          that.setData({
            data: data,
            show: true,
            button_name: button_name,
            form: form
          })
        }else{
          a.alert(t.msg);
        }
    },true)
    
  },

  //过滤字段，转换字段格式
  to_str: function (data,list) {
    var that = this, arr = [];
    for (let i in data) {
      arr.push({ 'name': i, 'value': data[i] });
    }
    if (arr.length > 0) {
      arr.forEach(function (k) {
        for (var i = 0; i < list.length; i++) {
          if (k.name == list[i].name) {
            if (list[i].module == 'checkbox') {
              data[k.name] = data[k.name].join(',');
            }
            // if (list[i].module == 'region') {//input自动转数组为字符串了
            //  // data[k.name] = data[k.name].join(',');
            // }
          }
        }
      })
      return data;
    } else {
      a.error('表单不能为空');
      return;
    }
  },

  //字段验证
  validate: function (data,list,obj) {
    var arr = [], n = 0, that = this;
    for (let i in data) {
      arr.push({ 'name': i, 'value': data[i] });
    }
    if (arr.length > 0) {
      for (var i = 0; i < arr.length; i++) {
        var res = that.in_array(arr[i].name, arr[i].value,list);
        if (res['code'] == 1) {
          n++;
          a.error(res.msg);
          break;
        }
      }
      "function" == typeof obj && obj(n)
    } else {
      a.error('表单不能为空');
      return;
    }
  },

  //错误判断
  in_array: function (name, value,list) {
    var data = { 'code': 0 };
    list.forEach(function (k) {
      if (k.name == name) {
        console.log(name);
        console.log(value);
        //判断不能为空
        if (k.empty) {
          if (!value || value.length==0) {//判断字段是否空值
            data['code'] = 1;
            data['msg'] = k.title+'不能为空';
            return data;//字段不能能为空
          }

        }
        // if (k.module == 'time_two') {

        // }
      }
    })
    return data;
  },
  
  /**
  * 图片上传
  * this
  * n文件夹名称
  * key 0多图上传，1单图上传
  */
  upload: function (that, field,n, key = 0) {
    var _this = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#f7982a",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            _this.chooseWxImage('album', that,field,n, key)
          } else if (res.tapIndex == 1) {
            _this.chooseWxImage('camera', that, field, n, key)
          }
        }
      }
    })
  },
  chooseWxImage: function (type_, that, field,n, key) {
    var _this = this,
      site = getApp().siteInfo,
      arr = that.data.data,
      url = site.siteroot + '?i=' + site.uniacid + '&t=undefined&v=' + site.version + '&from=wxapp&c=entry&a=wxapp&do=index_uploadFile&path=' + n + '&m=' + site.name + '&sign=5201314';
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: [type_],
      success: function (res) {
        //console.log(res)
        if (key == 0) {
          res.tempFilePaths.forEach(function (t) {
            // console.log(t)
            wx.uploadFile({
              url: url,
              filePath: t,
              name: 'file_upload',
              success: function (res) {
                console.log(res)
                if (res.data != null && res.data != '') {
                  var data = a.json_parse(res.data);
                  console.log(data)
                  if (data.code == 0) {
                    arr[field] = arr[field].concat(data.info);
                    that.setData({
                      data: arr
                    })
                  } else {
                    a.error(data.msg)
                  }
                }
              }
            })
          })
        } else {
          wx.uploadFile({
            url: url,
            filePath: res.tempFilePaths[0],
            name: 'file_upload',
            success: function (res) {
              console.log(res)
              if (res.data != null && res.data != '') {
                var data = a.json_parse(res.data);
                if (data.code == 0) {
                  //var arr = that.data.data;
                  arr[field] = data.info;
                  that.setData({
                    data: arr
                  })
                } else {
                  a.error(data.msg)
                }
              }
            }
          })
        }
      }
    })
  },
}